package com.qiongqi.datadir.handler;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

import static com.qiongqi.datadir.utils.json.JsonSerializer.OBJECT_MAPPER;
import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;
import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
import static org.apache.commons.lang3.StringUtils.isBlank;

@Slf4j
public class JacksonListTypeHandler<T> extends BaseTypeHandler<List<T>> {

    private final JavaType javaType;

    // 关键：通过构造器接收元素类型
    public JacksonListTypeHandler(Class<T> elementType) {
        this.javaType = OBJECT_MAPPER.getTypeFactory()
                .constructCollectionType(List.class, elementType);
        //OBJECT_MAPPER.activateDefaultTyping(OBJECT_MAPPER.getPolymorphicTypeValidator());
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    List<T> list, JdbcType jdbcType) throws SQLException {
        try {
            String json = isNotEmpty(list) ? OBJECT_MAPPER.writeValueAsString(list) : null;  // Jackson序列化
            ps.setString(i, json);
        } catch (JsonProcessingException e) {
            throw new SQLException("JSON序列化失败", e);
        }
    }

    /**
     * @param rs
     * @param columnName
     * @return
     * @throws SQLException
     */
    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJsonToList(rs.getString(columnName));
    }

    /**
     * @param rs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJsonToList(rs.getString(columnIndex));
    }

    /**
     * @param cs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJsonToList(cs.getString(columnIndex));
    }

    private List<T> parseJsonToList(String json) {
        if (isBlank(json) || equalsIgnoreCase("[]", json) || equalsIgnoreCase("5B5D",json)) {
            return Collections.emptyList(); // 返回空集合而非 null
        }

        try {
            // 添加此行
            return OBJECT_MAPPER.readValue(json, javaType);
        } catch (JsonProcessingException e) {
            log.error("解析失败，原始JSON:{},{}", json, e); // 记录完整错误
        }
        return Collections.emptyList();
    }
}
